package cn.lp207663436.dynamicmanager.interceptor;

import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 对所有的controller进行切入，未传入消息头则使用默认的数据源
 * @author luopeng
 * @date 2023/7/4 17:25:57
 * @email lp207663436@foxmail.com
 */
@Component
@Aspect
public class DsInterceptor implements HandlerInterceptor {

    private static final String DS_CHOOSE_HEADER = "poolName";

    @Resource
    private DynamicDataSourceProperties dynamicDataSourceProperties;

    @Pointcut("execution(public * *..controller..*(..))")
    public void dataSourcePointcut(){}

    @Before("dataSourcePointcut()")
    public void before() {
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
            assert attributes != null;
            HttpServletRequest request = attributes.getRequest();
            String header = request.getHeader(DS_CHOOSE_HEADER);
            if (StringUtils.isNotBlank(header)) {
                DynamicDataSourceContextHolder.push(header);
            } else {
                DynamicDataSourceContextHolder.push(dynamicDataSourceProperties.getPrimary());
            }
    }
}
